﻿using AutoMapper;
using MediatR;
using WMS.Api.Application.Commands.Users;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers.Users
{
    public class UpdUserCommandHandler : IRequestHandler<UpdUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> _userRepo;
        private readonly IMapper _mapper;

        public UpdUserCommandHandler(IBaseRepository<User> userRepo, IMapper mapper)
        {
            _userRepo = userRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>("修改用户");

            // 检查用户是否存在
            var existingUser = await _userRepo.GetAsync(request.UserId);
            if (existingUser == null)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "用户不存在";
                result.code = StatusCodeEnum.Fail;
                return result;
            }

            // 更新用户信息
            existingUser.UserCode = request.UserCode;
            existingUser.UserEmail = request.UserEmail;
            existingUser.UserName = request.UserName;
            existingUser.Phone = request.Phone;
            existingUser.Balance = request.Balance;

            var r = await _userRepo.UpdateAsync(existingUser);

            result.data = r;
            result.isSuc = true;
            result.msg = "修改成功";
            result.code = StatusCodeEnum.Ok;

            if (r < 0)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "修改失败";
                result.code = StatusCodeEnum.Fail;
            }

            return result;
        }
    }
}
